package com.wd.attend.controller.System;

import com.alibaba.fastjson2.JSONObject;
import com.wd.attend.domain.vo.LoginUserVo;
import com.wd.common.core.domain.HttpResponse;
import com.wd.framework.web.service.SysLoginService;
import com.wd.framework.web.service.SysPermissionService;
import com.wd.system.domain.SysMenu;
import com.wd.system.domain.SysUser;
import com.wd.system.domain.model.LoginBody;
import com.wd.system.service.ISysMenuService;
import com.wd.system.utils.SecurityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * @className: SysLoginController
 * @description: TODO 类描述
 * @author: liumingkun
 * @date: 2023/4/13
 **/
@RestController
public class SysLoginController {
    @Resource
    private SysLoginService loginService;

    @Resource
    private ISysMenuService menuService;

    @Resource
    private SysPermissionService permissionService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/session/login")
    public HttpResponse login(@RequestBody LoginBody loginBody) {
        System.out.println(JSONObject.toJSONString(loginBody));
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        return HttpResponse.successData(token);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @PostMapping("/session/getUserInfo")
    public HttpResponse getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setUser(user);
        loginUserVo.setRoles(roles);
        loginUserVo.setPermissions(permissions);
        return HttpResponse.successData(loginUserVo);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("/session/getRouters")
    public HttpResponse getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return HttpResponse.successData(menuService.buildMenus(menus));
    }

    @PostMapping("/session/logout")
    public HttpResponse logout() {
        // TODO: 2023/6/21 登出逻辑需要完善 
        return HttpResponse.success();
    }
}